package com.code;

import java.sql.DriverManager;

import com.database.DBSystem;
import com.example.R;
//import com.test.TelephonyInfo;
import com.Global.Global;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class Login extends Activity {
	private EditText txtServerNameWifi, txtServerName3G, txtPort, txtLogin,
			txtPassword, txtDatabaseName, etChiNhanh;
	private CheckBox chbRemember;
	private Button btnConnect, btnCancel;
	private RadioButton radSNWifi, radSN3G;
	private DBSystem dbHelper;
	private static int REQUESTCODE_LOGINCONFIG = 100;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		//khang-test
//		TelephonyManager telMgr = (TelephonyManager) this
//				.getSystemService(Context.TELEPHONY_SERVICE);
//		String deviceID = telMgr.getDeviceId();
//		String simSerialNumber = telMgr.getSimSerialNumber();
//		String simLineNumber = telMgr.getLine1Number();
//		
//		WifiManager wimanager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
//	    String macAddress = wimanager.getConnectionInfo().getMacAddress();
//	    if (macAddress == null) {
//	        macAddress = "Device don't have mac address or wi-fi is disabled";
//	    }
//	    
//	    TelephonyInfo telephonyInfo = TelephonyInfo.getInstance(this);
//        String imeiSIM1 = telephonyInfo.getImeiSIM1();
//        String imeiSIM2 = telephonyInfo.getImeiSIM2();
//        boolean isSIM1Ready = telephonyInfo.isSIM1Ready();
//        boolean isSIM2Ready = telephonyInfo.isSIM2Ready();
//
//        boolean isDualSIM = telephonyInfo.isDualSIM();
//        String a = " IME1 : " + imeiSIM1 + "\n" +
//                " IME2 : " + imeiSIM2 + "\n" +
//                " IS DUAL SIM : " + isDualSIM + "\n" +
//                " IS SIM1 READY : " + isSIM1Ready + "\n" +
//                " IS SIM2 READY : " + isSIM2Ready + "\n";
        //khang-test-end
        

		radSNWifi = (RadioButton) findViewById(R.id.radSNWifi);
		radSN3G = (RadioButton) findViewById(R.id.radSN3G);
		txtServerNameWifi = (EditText) findViewById(R.id.txtServerNameWifi);
		txtServerName3G = (EditText) findViewById(R.id.txtServerName3G);
		txtPort = (EditText) findViewById(R.id.txtPort);
		txtLogin = (EditText) findViewById(R.id.txtLogin);
		txtPassword = (EditText) findViewById(R.id.txtPassword);
		txtDatabaseName = (EditText) findViewById(R.id.txtDatabaseName);
		etChiNhanh = (EditText) findViewById(R.id.etChiNhanh);
		chbRemember = (CheckBox) findViewById(R.id.chbRemember);
		btnConnect = (Button) findViewById(R.id.btnConnect);
		btnCancel = (Button) findViewById(R.id.btnCancel);

		// check connect remember
		if (connectRemember()) {
			Intent intent = new Intent(Login.this, Main.class);
			startActivity(intent);
			Login.this.finish();
		}
		//Login while config
		else{
			if(!LoginConfig.login)
			startActivityForResult(new Intent(Login.this,
					LoginConfig.class), REQUESTCODE_LOGINCONFIG);
		}
		
		//load data
		loadDataToLogin();

		btnConnect.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				if (isConnect()) {
					Toast.makeText(Login.this,
							"Kết nối đến server thành công!", Toast.LENGTH_LONG)
							.show();
					Intent intent = new Intent(Login.this, Main.class);
					startActivity(intent);
					Login.this.finish();
				}
			}
		});

		btnCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Login.this.finish();
			}
		});

	}

	public Boolean isConnect() {
		try {
			String serverName = "";
			String serverPort = "";
			String dbName = "";
			String userSQL = "";
			String passSQL = "";
			String strStaticServerName = "";
			if (radSNWifi.isChecked()) {
				strStaticServerName = "wifi";
				serverName = txtServerNameWifi.getText().toString();
			} else {
				strStaticServerName = "3g";
				serverName = txtServerName3G.getText().toString();
			}

			String driver = "net.sourceforge.jtds.jdbc.Driver";
			Class.forName(driver).newInstance();
			serverPort = txtPort.getText().toString();
			dbName = txtDatabaseName.getText().toString();
			userSQL = txtLogin.getText().toString();
			passSQL = txtPassword.getText().toString();
			String url = "jdbc:jtds:sqlserver://" + serverName + ":"
					+ serverPort + ";DatabaseName=" + dbName
					+ ";integratedSecurity=true;user=" + userSQL + ";password="
					+ passSQL + "";
			DriverManager.getConnection(url);

			String strRemember = "0";
			if (chbRemember.isChecked())
				strRemember = "1";

			// update remember
			DBSystem dbcv = new DBSystem(Login.this);
			dbcv.open();
			dbcv.Update(txtServerNameWifi.getText().toString(), txtPort
					.getText().toString(), txtLogin.getText().toString(),
					txtPassword.getText().toString(), txtDatabaseName.getText()
							.toString(), strRemember, "1", etChiNhanh.getText()
							.toString(), txtServerName3G.getText().toString(),
					strStaticServerName);
			Global.ServerName = serverName;
			Global.ServerPort = serverPort;
			Global.Login = userSQL;
			Global.Password = passSQL;
			Global.DatabaseName = dbName;
			Global.ChiNhanh = etChiNhanh.getText().toString();
			Global.StatusServerName = strStaticServerName;
			dbcv.close();
			return true;
		} catch (Exception e) {
			Toast.makeText(Login.this,
					"Kết nối đến server thất bại.\nChi tiết: " + e.toString(),
					Toast.LENGTH_LONG).show();

			// update remember ->0
//			DBSystem dbcv = new DBSystem(Login.this);
//			dbcv.open();
//			dbcv.UpdateRemember("0");
//			dbcv.close();
			return false;
		}
	}

	public Boolean connectRemember() {
		dbHelper = new DBSystem(this);
		dbHelper.open();
		Cursor cur = dbHelper.SelectSystemAll();
		String strServerNameWifi = "";
		String strServerPort = "";
		String strLogin = "";
		String strPassword = "";
		String strDatabaseName = "";
		String strRemember = "";
		String strChiNhanh = "";
		String strServerName3G = "";
		String strStatusServerName = "";
		if (cur != null) {
			while (cur.moveToNext()) {
				strServerNameWifi = cur.getString(1).toString();
				strServerPort = cur.getString(2).toString();
				strLogin = cur.getString(3).toString();
				strPassword = cur.getString(4).toString();
				strDatabaseName = cur.getString(5).toString();
				strRemember = cur.getString(6).toString();
				strChiNhanh = cur.getString(8).toString();
				strServerName3G = cur.getString(9).toString();
				strStatusServerName = cur.getString(10).toString();
			}
		}
		cur.close();
		try {
			if (strRemember.equals("1")) {
				if (strStatusServerName.equals("wifi")) {
					Global.ServerName = strServerNameWifi;
					Global.StatusServerName = "wifi";
				} else {
					Global.ServerName = strServerName3G;
					Global.StatusServerName = "3g";
				}
				Global.ServerPort = strServerPort;
				Global.Login = strLogin;
				Global.Password = strPassword;
				Global.DatabaseName = strDatabaseName;
				Global.ChiNhanh = strChiNhanh;
				String url = "jdbc:jtds:sqlserver://" + Global.ServerName + ":"
						+ strServerPort + "; DatabaseName=" + strDatabaseName
						+ ";integratedSecurity=true;user=" + strLogin
						+ ";password=" + strPassword + "";
				String driver = "net.sourceforge.jtds.jdbc.Driver";
				Class.forName(driver).newInstance();
				DriverManager.getConnection(url);
				dbHelper.close();
				return true;
			} else {
				txtServerNameWifi.setText(strServerNameWifi);
				txtServerName3G.setText(strServerName3G);
				txtPort.setText(strServerPort);
				txtLogin.setText(strLogin);
				txtPassword.setText(strPassword);
				txtDatabaseName.setText(strDatabaseName);
				dbHelper.close();
				return false;
			}
		} catch (Exception e) {
			dbHelper.close();
			return false;
		}
	}

	public void loadDataToLogin() {
		dbHelper = new DBSystem(this);
		dbHelper.open();
		Cursor cur = dbHelper.SelectSystemAll();
		if (cur != null) {
			while (cur.moveToNext()) {
				txtServerNameWifi.setText(cur.getString(1).toString());
				txtServerName3G.setText(cur.getString(9).toString());
				txtPort.setText(cur.getString(2).toString());
				txtLogin.setText(cur.getString(3).toString());
				txtPassword.setText(cur.getString(4).toString());
				txtDatabaseName.setText(cur.getString(5).toString());
				if (cur.getString(10).toString().equals("wifi")) {
					radSNWifi.setChecked(true);
					radSN3G.setChecked(false);
				} else {
					radSNWifi.setChecked(false);
					radSN3G.setChecked(true);
				}
			}
		}
		cur.close();
		dbHelper.close();
	}

}
